package cn.ljn.system.service.impl;

import cn.ljn.system.domain.Menu;
import cn.ljn.system.service.IMenuService;
import cn.ljn.basic.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljn
 * @since 2023-03-09
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Override
    public List<Menu> first() {

        return super.findAll().stream().filter(menu -> menu.getParentId() == null).collect(Collectors.toList());
    }

    @Override
    public List<Menu> tree() {
        List<Menu> result = new ArrayList<>();

        // 查询全部
        List<Menu> all = super.findAll();
        Map<Long, Menu> map = all.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));

        all.forEach(menu -> {
            if (menu.getParentId() == null){
                result.add(menu);
            }else {
                Menu menu1 = map.get(menu.getParentId());
                if (menu1 != null){
                    menu1.getChildren().add(menu);
                }
            }
        });

        return result;
    }
}
